package com.education.webservlet;

import com.education.db.HibernateSessionFactory;
import com.education.db.dao.InfoFileDAO;
import com.education.db.domain.InfoFile;
import com.education.service.bean.ActivityBean;
import com.education.util.Constant;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.Transaction;
/**
 * Created by Fan307 on 2016/12/5.
 */
@WebServlet(name = "FindKeyWordServlet")
public class FindKeyWordServlet extends HttpServlet {
    private Transaction tran;
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding(Constant.CHAR_ENCODING);
        String keyword = request.getParameter("keyword");
        tran = HibernateSessionFactory.getSession().getTransaction();
        try{
            tran.begin();
            InfoFileDAO infoFileDAO = new InfoFileDAO();
            List<InfoFile> infoFiles = infoFileDAO.findByKeyWord(keyword);
            List<ActivityBean> infoFileBean = new ArrayList<>();
            for(InfoFile infoFile:infoFiles)
            {
                ActivityBean infofilebean = new ActivityBean();
                infofilebean.setName(infoFile.getFileName());
                infofilebean.setPath(infoFile.getFilePath());
                infoFileBean.add(infofilebean);
            }
            request.setAttribute("infofilebean", infoFileBean);
            request.getRequestDispatcher("/Pages/findKeyWord.jsp").forward(request, response);
            tran.commit();
        }catch(Exception e) {
            e.printStackTrace();
            System.out.println(e.toString());
            tran.rollback();
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
